﻿using ImageResizer;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UpdateDesktopDocHtmlContent.Properties;

namespace UpdateDesktopDocHtmlContent
{
    internal class ResizedImageHelper
    {
        public int ImageCount { get;private set; }
        public int CurrentImageIndex { get; private set; }
        public event EventHandler OnImageProcess;
        private string m_dir;
        private string m_cacheDir;
        private StreamWriter log;

        /// <summary>
        /// 传入的是Ngix的地址
        /// </summary>
        /// <param name="dir"></param>
        public ResizedImageHelper(string dir)
        {
            m_dir = dir;

            var cacheDir = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "imgCache_" + Path.GetFileNameWithoutExtension(dir));
            if (Directory.Exists(cacheDir) == false)
            {
                Directory.CreateDirectory(cacheDir);
            }
            m_cacheDir= cacheDir;

            log = File.CreateText(cacheDir + "//a.log");
        }

        public void ProcessDirectory()
        {
            try
            {
                var files = new DirectoryInfo(m_dir);

                var pngs = files.GetFiles("*.png", SearchOption.AllDirectories);
                var jpegs = files.GetFiles("*.jpg", SearchOption.AllDirectories);
                var bmps = files.GetFiles("*.bmp", SearchOption.AllDirectories);

                List<FileInfo> list = new List<FileInfo>();
                list.AddRange(pngs);
                list.AddRange(jpegs);
                list.AddRange(bmps);

                ImageCount = list.Count;

                var cacheItems = new DirectoryInfo(m_cacheDir).GetFiles();
                var dirUse=new Dictionary<string, bool>();
                foreach (var item in cacheItems)
                {
                    dirUse.Add(item.Name, false);
                }

                for (var i = 0; i < list.Count; i++)
                {
                    if (GetMinFileName(list[i], dirUse) == false)
                    {
                        log.WriteLine("GetMinFileName create:" + list[i].FullName);
                        var isOk = ResizeImage(list[i], out string maxFileName);
                        if (isOk)
                        {
                            var disFile = Path.Combine(m_cacheDir, list[i].Name);
                            log.WriteLine("GetMinFileName newCopy:" + disFile);
                            File.Copy(list[i].FullName, disFile);
                        }
                    }

                    CurrentImageIndex = i;
                    if (OnImageProcess != null)
                    {
                        OnImageProcess(this, null);
                    }
                }
                log.Flush();
                log.Close();

                foreach(var item in dirUse.Keys)
                {
                    if (dirUse[item] == false)
                    {
                        File.Delete(item);
                    }
                }
            }
            catch (Exception err)
            {
                log.WriteLine(err.Message);
                log.WriteLine(err.StackTrace);
                log.Close();
            }
            
        }
        private bool GetMinFileName(FileInfo fileName, Dictionary<string, bool> cacheItems)
        {
            var minFileName = Path.Combine(m_cacheDir, fileName.Name);
            if (File.Exists(minFileName))
            {
                log.WriteLine("GetMinFileName Copyed:" + minFileName);
                cacheItems[minFileName] = true;
                var maxFile = Path.ChangeExtension(fileName.FullName, ".mx" + fileName.Extension);
                File.Copy(fileName.FullName, maxFile, true);
                File.Copy(minFileName, fileName.FullName, true);

                return true;
            }
            return false;
        }
        private bool ResizeImage(FileInfo fileName,out string maxFileName)
        {
            var newWidth = 0;
            var newHeight = 0;
            try
            {
                var maxFile = Path.ChangeExtension(fileName.FullName, ".mx" + fileName.Extension);
                maxFileName = maxFile;
                File.Copy(fileName.FullName, maxFile, true);

                Bitmap originalImage = new Bitmap(fileName.FullName);

                // 设置目标缩放尺寸
                newWidth = (int)(originalImage.Width * 0.75);
                newHeight = (int)(originalImage.Height * 0.75);
                originalImage.Dispose();

                ImageResizer.ImageBuilder.Current.Build(maxFile, fileName.FullName, new ResizeSettings()
                {
                    Height = newHeight,
                    Width = newWidth,
                });
                return true;
            }
            catch (Exception err)
            {
                maxFileName = null;
                return false;
                //MessageBox.Show("图片:" + fileName + "不能被处理,目标图片尺寸" + newWidth + "," + newHeight + "\r\n原因:" + err.Message);
            }
           
        }
    }

    public class FileInfoOfSize
    {
        public long Size { get; set; }
        public string KeyFileName { get; set; }
        public string FullFileName { get; set; }
        public bool IsUsed { get; set; } = false;
        public bool IsMxFile { get; set; } = false;

        public FileInfoOfSize(string fileItem)
        {
            this.FullFileName = fileItem;
            this.Size = new FileInfo(fileItem).Length;
            this.KeyFileName = GetKeyFileName(fileItem, out bool isMxFile);
            this.IsMxFile = isMxFile;
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileItem"></param>
        /// <param name="deleteFile"></param>
        /// <returns></returns>
        public static string GetKeyFileName(string fileItem,out bool isMaxFile)
        {
            var ts = Path.GetFileNameWithoutExtension(fileItem).Split('.');
            int k = 1;
            if (ts[ts.Length - 1] == "mx")
            {
                isMaxFile=true;
                k = 2;
            }
            else
            {
                isMaxFile=false;
            }
            var str = "";
            for (var i = 0; i < ts.Length - k; i++)
            {
                if (i != 0) str += ".";
                str += ts[i];
            }
            return str;
        }
    }
}
